/*
 * Copyright (c) 2023 Huawei Technologies Co.,Ltd.
 *
 * openGauss is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *          http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package demo;

import connectionpool.C3P0Executor;
import org.apache.log4j.Logger;
import testcase.QuickAutoBalanceTest;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 */
public class C3P0QuickAutoBalanceTest {
  
  private static Logger LOGGER = Logger.getLogger(QuickAutoBalanceTest.class);
  
  private static C3P0Executor c3P0Executor;
  
  // 使用c3p0创建一批连接池，全部都是空闲状态，在此期间重启数据库。
  private static void c3p0QuickAutoBalanceAllIdleTest(String url, String username, String password, int
      minIdle, int maxSize) {
    LOGGER.info("使用c3p0创建一批连接池，全部都是空闲状态，在此期间重启数据库。观察jdbc日志输出和pg_stat_activity查询结果");
    c3P0Executor = new C3P0Executor(url, username, password, minIdle, maxSize);
    while (true) {
      // 在此期间，关闭数据库，过一段时间重启数据库。
      try {
        int num = 0;
        List<Connection> connections = new ArrayList<>();
        while (num < minIdle) {
          try {
            Connection connection = c3P0Executor.getConnection();
            connections.add(connection);
          } catch (SQLException e) {
            throw new RuntimeException(e);
          }
          num ++;
        }
        for (Connection connection : connections) {
          try {
            connection.close();
          } catch (SQLException e) {
            throw new RuntimeException(e);
          }
        }
        Thread.sleep(1000 * 10);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }
  }
  
  private static void c3p0QuickAutoBalanceSomeIdleTest(String url, String username, String password, int
      minIdle, int maxSize) {
    LOGGER.info("使用c3p0创建一批连接池，其中3/4是空闲状态，在此期间重启数据库。观察jdbc日志输出和pg_stat_activity查询结果");
    c3P0Executor = new C3P0Executor(url, username, password, minIdle, maxSize);
    int inQuery = minIdle / 4;
  
    List<Connection> inQueryConnections = new ArrayList<>();
    for (int i = 0; i < inQuery; i++) {
      Connection connection = null;
      try {
        connection = c3P0Executor.getConnection();
      } catch (SQLException e) {
        throw new RuntimeException(e);
      }
      inQueryConnections.add(connection);
    }
    while (true) {
      try {
        for (Iterator<Connection> iterator = inQueryConnections.iterator(); iterator.hasNext();) {
          Connection connection = iterator.next();
          try {
            if (!connection.isValid(2)) {
              iterator.remove();
            } else {
              Statement statement = connection.createStatement();
              statement.execute("select 1");
              statement.execute("select 2");
              statement.close();
            }
          } catch (SQLException e) {
            throw new RuntimeException(e);
          }
        }
        int num = 0;
        List<Connection> connections = new ArrayList<>();
        while (num < minIdle - minIdle / 4) {
          try {
            Connection connection = c3P0Executor.getConnection();
            connections.add(connection);
          } catch (SQLException e) {
            throw new RuntimeException(e);
          }
          num ++;
        }
        for (Connection connection : connections) {
          try {
            connection.close();
          } catch (SQLException e) {
            throw new RuntimeException(e);
          }
        }
        Thread.sleep(1000 * 5);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }
  }
  
  public static void main(String[] args) {
    LOGGER.info("Testcase: case1, case2, case3.");
    if (args.length < 6) {
      LOGGER.error("request params: testCaseName url username password minIdle maxSize.");
      return;
    }
    String url = args[1];
    String username = args[2];
    String password = args[3];
    int minIdle = Integer.parseInt(args[4]);
    int maxSize = Integer.parseInt(args[5]);
    if ("case1".equals(args[0])) {
      c3p0QuickAutoBalanceAllIdleTest(url, username, password, minIdle, maxSize);
    }
    if ("case2".equals(args[0])) {
      c3p0QuickAutoBalanceSomeIdleTest(url, username, password, minIdle, maxSize);
    }
  }
}
